import React, {Fragment, useMemo, useState} from "react";
import {Select, Badge, Row, Col} from 'antd';

import { helper } from 'vendor/utils/T';
import prompt from "vendor/utils/prompt";

import { startAccount, stopAccount } from '../api';
import {EnumAccountStatus, EnumAccountStatusList} from './constants';

interface AccountStatusProps{
    accountId: string;
    status: "0" | "1"
}

const AccountStatus: React.FC<AccountStatusProps> = ({accountId, status}) =>{
    const statusTValue = useMemo(() => helper.convertArrayToObj(EnumAccountStatusList), [])
    const [ saving, setSaving ] = useState(false);
    const [editing, setEditing] = useState(false);
    const [realStatus, setRealStatus] = useState<string>(status);

    const handleStatusChange = (value: string) => {
        setSaving(true);
        const successCallback = () => {
            setRealStatus(value);
            setEditing(!editing);
            setSaving(false);
            prompt.success("操作成功")
        }

        const failedCallback = (val: string) => {
            setSaving(false);
            setRealStatus(val)
        }

        switch (value){
            case EnumAccountStatus.normal:
                startAccount(accountId).then(successCallback).catch(() => {
                    failedCallback(EnumAccountStatus.stop)
                })
                break;
            case EnumAccountStatus.stop:
                stopAccount(accountId).then(successCallback).catch(() => {
                    failedCallback(EnumAccountStatus.normal)
                })
                break;
        }
    }

    return <Fragment>
        {!editing && <div
            style={{width: "100%"}}
            title={"双击修改状态"}
            onDoubleClick={() => setEditing(!editing)}
        ><Badge color={statusTValue[realStatus]?.color} text={statusTValue[realStatus]?.label ?? "-"} /></div>}

        {editing && <Row gutter={5} align="middle">
            <Col span={20}>
                <Select
                    loading={saving}
                    value={realStatus}
                    onChange={handleStatusChange}
                    style={{width: "100%"}}
                >
                    {EnumAccountStatusList.map(({label, value}) => <Select.Option key={value} value={value}>{label}</Select.Option>)}
                </Select>
            </Col>
            <Col style={{cursor: "pointer"}} onClick={() => setEditing(!editing)}>取消</Col>
        </Row>}
    </Fragment>
}

export default AccountStatus;